package org.example.wine.boot.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.wine.boot.utils.JwtUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.util.Map;

/**
 * @author Administrator
 * token拦截器
 */
@Component
public class LoginInterceptors implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String token = request.getHeader("token");
            if (token == null) {
                // 如果token为空，则直接返回false
                sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token不存在");
                return false;
            }

            Map<String, Object> claims = JwtUtils.parseToken(token);
            if (claims != null) {
                // 如果解析成功，则继续处理请求
                return true;
            } else {
                // 如果解析失败，则发送错误响应
                sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "token验证错误");
                return false;
            }
        } catch (Exception e) {
            // 异常处理，记录日志并发送错误响应
            sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "请求失败" + e.getMessage());
            return false;
        }
    }

    private void sendErrorResponse(HttpServletResponse response, int statusCode, String errorMessage) throws IOException {
        try {
            response.setStatus(statusCode);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            JSONObject json = new JSONObject();
            json.put("error", errorMessage);
            json.put("code", statusCode);
            response.getWriter().write(json.toString());
        } catch (Exception e) {
            response.getWriter().write("接口报错");
        }

    }
}
